import {ref} from 'vue'
import { ElMessage } from 'element-plus'
export function useDevice(){
    const hasAudioInput=ref(false)
    const hasVideoInput=ref(false)
    const videoRef=ref()
    let videoStream=null
    let audioStream=null
    const tip=ref('')

   async function init(){
    //获取系统里面枚举的设备的列表
        const devices = await navigator.mediaDevices.enumerateDevices()
        const audioInput=devices.find((item)=>(item.kind==='audioinput'))
        const videoInput=devices.find((item)=>(item.kind==='videoinput'))
        const audioOutput=devices.find((item)=>(item.kind==='audiooutput'))
        hasVideoInput.value=!!videoInput?.deviceId
        hasAudioInput.value=!!audioInput?.deviceId
        if(hasVideoInput.value){
            openVideo()
        }else{
            tip.value='摄像头处于关闭状态';
        }
    }
    init()
    async function openMicro(){
        audioStream=await navigator.mediaDevices.getUserMedia({audio:true})
        hasAudioInput.value=true
        
    }
    function closeMicro(){
        hasAudioInput.value=false
       
        const audioTracks=audioStream?.getTracks()
        for(const audioTrack of audioTracks){
           audioTrack.stop()
        }
        tip.value='摄像头处于关闭状态'
    }

    async function openVideo(){
        try{
            tip.value='摄像头开启中'
            videoStream=await navigator.mediaDevices.getUserMedia({video:true})
            videoRef.value.srcObject=videoStream
            hasVideoInput.value=true
        }catch(e){
            let message =''
            if(['NotAllowedError','PermissionDeniedError'].includes(e.name)) {
                message ='用户拒绝授子摄像头权限'
                     tip.value='用户拒绝授子摄像头权限'
            }else if(['NotFoundError','DevicesNotFoundError'].includes(e.name)){
                message ='没有找到可用的摄像头设备'
                tip.value='没有找到可用的摄像头设备'
            }else if('evice in use'.includes(e.name)){
               message='摄像头被其他程序占用'
               tip.value='摄像头被其他程序占用'
            }   
            ElMessage.error(message||'摄像头开启出错')
             
        }
     
    }
    function closeVideo(){
        hasVideoInput.value=false
        videoRef.value.srcObject=null
        const videoTracks=videoStream?.getTracks()
        for(const videoTrack of videoTracks){
            videoTrack.stop()
        }
        tip.value='摄像头处于关闭状态'

    }
    return {
        openMicro,
        closeMicro,
        openVideo,
        closeVideo,
        hasVideoInput,
        hasAudioInput,
        videoRef,
        tip
    }
}